from flask import jsonify


class APIError(Exception):
    def __init__(self, code, msg):
        Exception.__init__(self)
        self.code = code
        self.msg = msg

    def to_dict(self):
        return {'code': self.code, 'msg': self.msg, 'data':{}}


def error_403_handler(error):
    resp = jsonify({'code': 403, 'msg': 'permission not allowed', 'data': None})
    resp.status_code = 403
    return resp


def error_404_handler(error):
    resp = jsonify({'code': 404, 'msg': 'not found', 'data': None})
    resp.status_code = 404
    return resp


def error_405_handler(error):
    resp = jsonify({'code': 405, 'msg': 'Method not Allowed', 'data': None})
    resp.status_code = 405
    return resp


def error_429_handler(error):
    resp = jsonify({'code': 429, 'msg': 'to many requests', 'data': None})
    resp.status_code = 429
    return resp


def error_500_handler(error):
    resp = jsonify({'code': 500, 'msg': 'server error', 'data': None})
    resp.status_code = 500
    return resp


def error_handler(error):
    resp = jsonify(error.to_dict())
    resp.status_code = 500
    return resp
